
package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.dao.generic.AutoKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.Referer;

public class GenericRefererDAO extends AutoKeys implements
		org.jetnuke.dao.RefererDAO {

	/* (non-Javadoc)
	 * @see org.jetnuke.model.RefererModel#selectAll()
	 */
	public List selectAll() throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("RefererModel.selectAll"));
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.RefererModel#deleteAll()
	 */
	public void deleteAll() throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("RefererModel.deleteAll"));
		p.executeUpdate();
		p.close();
		
	}
	protected List processSelectAll(ResultSet rs) throws Exception  {
		List list = new ArrayList();
		while (rs.next()) {
			Referer u = new Referer();
			fillRefererFromResultSet(u,rs);			
			list.add(u);
		}
		
		return list;
	}

	/**
	 * @param u
	 * @param rs
	 */
	private void fillRefererFromResultSet(Referer u, ResultSet rs)  throws Exception{
		u.setRID(rs.getInt("RID"));
		u.setURL(rs.getString("URL"));
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.RefererModel#countAll()
	 */
	public int countAll() throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("RefererModel.countAll"));
		
		ResultSet rs = p.executeQuery();
		rs.next();
		
		int r= rs.getInt(1);
		rs.close();
		p.close();
		return r;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.RefererModel#selectOrderRID(int)
	 */
	public List selectOrderRID(int limit) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("RefererModel.selectOrderRID"));
		p.setInt(1,limit);
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.RefererModel#addNew(org.jetnuke.entities.Referer)
	 */
	public int addNew(Referer ref) throws Exception {
		PreparedStatement p = this.getStatementForAutoKeys("RefererModel.addNew");
		
		initNewReferer(ref, p);
		
		int id = this.executeAutoKeysQuery(p);
				
		return id;
	}

	/**
	 * @param ref
	 * @param p
	 */
	protected void initNewReferer(Referer ref, PreparedStatement p)throws Exception {
		p.setString(1,ref.getURL());
	}

}
